 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.wh.transaction.distributiontomainkitchen;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterRegional;
import com.ronsicecream.pos.entities.PosMasterStatus;
import com.ronsicecream.pos.entities.PosMasterUnit;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.entities.PosTransactionMkDistributionToOutlet;
import com.ronsicecream.pos.entities.PosTransactionOutRequestMaterialToWarehouse;
import com.ronsicecream.pos.entities.PosTransactionOutRequestToMainkitchen;
import com.ronsicecream.pos.entities.PosTransactionWhDistributionToMainkitchen;
import com.ronsicecream.pos.entities.PosTransactionWhDistributionToMainkitchenDetail;
import com.ronsicecream.pos.entities.PosTransactionWhDistributionToOutlet;
import com.ronsicecream.pos.entities.PosTransactionWhDistributionToOutletDetail;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.master.status.Status;
import com.ronsicecream.pos.wh.transaction.distributiontomainkitchendetail.DistributionDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author user
 */
public class Distribution extends Page {

    private Field distributionId;
    private Field distributionDistributorBy;
    private Field distributionNumber;
    private Field distributionCost;
    private Field distributionTotal;
    private Field distributionPaid;
    private Field distributionUnpaid;
    private Field distributionSent;
    private Field distributionUnsent;
    private Field distributionKeel;
    private Field distributionDate;
    private Field distributionDescription;
    private Field distributionTimestamp;
    private Field distributionUserId;
    private Field distributionUnitId;
    private Field distributionRegionalId;
    private Field distributionPosUnitId;
    private Field distributionRequestId;
//    private Action actionRevision = new Action("revisi", "Revision Distribution");
//    private Action actionReject = new Action("reject", "Reject Distribution");
//    private Action actionAgree = new Action("approve", "Agree Distribution");

    public Distribution() {
        super();

        setTheClass(PosTransactionWhDistributionToOutlet.class);

        setPageDetail(DistributionDetail.class);


        distributionId = new Field();
        distributionId.setName("distributionId");
        distributionId.setCaption(" id");
        distributionId.setInfo("distribution id");
        distributionId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        distributionId.setInputProperties(" size=\"20\"");
        getFields().add(distributionId);

        distributionDistributorBy = new Field();
        distributionDistributorBy.setName("distributionDistributorBy");
        distributionDistributorBy.setCaption("distributor by");
        distributionDistributorBy.setRequired(true);
        distributionDistributorBy.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionDistributorBy.setInputProperties(" size=\"20\"");
        getFields().add(distributionDistributorBy);

        distributionNumber = new Field();
        distributionNumber.setName("distributionNumber");
        distributionNumber.setCaption("number");
        distributionNumber.setRequired(true);
        distributionNumber.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionNumber.setInputProperties(" size=\"30\" readonly");
        getFields().add(distributionNumber);

        distributionCost = new Field();
        distributionCost.setName("distributionCost");
        distributionCost.setCaption("cost");
        distributionCost.setRequired(true);
        distributionCost.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        distributionCost.setInputProperties(" size=\"20\"");
        getFields().add(distributionCost);

        distributionTotal = new Field();
        distributionTotal.setName("distributionTotal");
        distributionTotal.setCaption("total");
        distributionTotal.setInfo("distribution total");
        distributionTotal.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        distributionTotal.setInputProperties(" size=\"20\"");
        getFields().add(distributionTotal);

        distributionPaid = new Field();
        distributionPaid.setName("distributionPaid");
        distributionPaid.setCaption("paid");
        //distributionPaid.setInfo("distribution paid");
        distributionPaid.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        distributionPaid.setInputProperties(" size=\"20\"");
        getFields().add(distributionPaid);

        distributionUnpaid = new Field();
        distributionUnpaid.setName("distributionUnpaid");
        distributionUnpaid.setCaption("unpaid");
        //distributionUnpaid.setInfo("distribution unpaid");
        distributionUnpaid.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        distributionUnpaid.setInputProperties(" size=\"20\"");
        getFields().add(distributionUnpaid);

        distributionSent = new Field();
        distributionSent.setName("distributionSent");
        distributionSent.setCaption("Sent");
        distributionSent.setInfo("distribution unpaid");
        distributionSent.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        distributionSent.setInputProperties(" size=\"20\"");
        getFields().add(distributionSent);

        distributionUnsent = new Field();
        distributionUnsent.setName("distributionUnsent");
        distributionUnsent.setCaption("unsent");
        distributionUnsent.setInfo("distribution unpaid");
        distributionUnsent.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        distributionUnsent.setInputProperties(" size=\"20\"");
        getFields().add(distributionUnsent);

        distributionKeel = new Field();
        distributionKeel.setName("distributionKeel");
        distributionKeel.setCaption("keel");
        //distributionKeel.setInfo("distribution keel");
        distributionKeel.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        distributionKeel.setInputProperties(" size=\"20\"");
        getFields().add(distributionKeel);

        distributionDate = new Field();
        distributionDate.setName("distributionDate");
        distributionDate.setCaption("date");
        distributionDate.setRequired(true);
        distributionDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        distributionDate.setInputProperties(" size=\"8\"");
        distributionDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(distributionDate);

//        distributionProgress = new Field();
//        distributionProgress.setName("distributionProgress");
//        distributionProgress.setCaption("progress");
//        //distributionProgress.setInfo("distribution progress");
//        distributionProgress.setListProperties(" align=\"left\" width=\"1%\" nowrap");
//        distributionProgress.setInputProperties(" size=\"20\"");
//        getFields().add(distributionProgress);

        distributionDescription = new Field();
        distributionDescription.setName("distributionDescription");
        distributionDescription.setCaption("description");
        distributionDescription.setInfo("distribution description");
        distributionDescription.setListProperties(" align=\"left\" width=\"25%\" nowrap");
        distributionDescription.setInputProperties(" size=\"20\"");
        distributionDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        distributionDescription.setInputType(Field.INPUT_TEXT_AREA);
        distributionDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(distributionDescription);

        distributionTimestamp = new Field();
        distributionTimestamp.setName("distributionTimestamp");
        distributionTimestamp.setCaption("timestamp");
        distributionTimestamp.setInfo("distribution timestamp");
        distributionTimestamp.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        distributionTimestamp.setInputProperties(" size=\"12\"");
//        distributionTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(distributionTimestamp);

        distributionUserId = new Field();
        distributionUserId.setName("distributionUserId");
        distributionUserId.setCaption("user");
        distributionUserId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        distributionUserId.setInputProperties(" size=\"20\"");
        getFields().add(distributionUserId);

        distributionUnitId = new Field();
        distributionUnitId.setName("distributionUnitId");
        distributionUnitId.setCaption("unit");
        distributionUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        distributionUnitId.setInputProperties(" size=\"20\"");
        getFields().add(distributionUnitId);

        distributionRegionalId = new Field();
        distributionRegionalId.setName("distributionRegionalId");
        distributionRegionalId.setCaption("regional");
        distributionRegionalId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionRegionalId.setInputProperties(" size=\"20\"");
        getFields().add(distributionRegionalId);

        distributionPosUnitId = new Field();
        distributionPosUnitId.setName("distributionPosUnitId");
        distributionPosUnitId.setCaption("pos unit");
        distributionPosUnitId.setRequired(true);
        distributionPosUnitId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionPosUnitId.setInputProperties(" size=\"20\"");
        getFields().add(distributionPosUnitId);

        distributionRequestId = new Field();
        distributionRequestId.setName("distributionRequestId");
        distributionRequestId.setCaption("request");
        distributionRequestId.setSelectorLoad(true);
        distributionRequestId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionRequestId.setInputProperties(" size=\"20\"");
        distributionRequestId.setSelectorCondition(" t.requestProgress='4'");
        distributionRequestId.getSelectorColumns().add(new String[]{"requestNumber", "Number", " align=\"center\" width=\"20%\" nowrap"});
//        returReceiptId.getSelectorColumns().add(new String[]{"receiptTotal", " Total ", "align=\"right\" width=\"10%\""});
        distributionRequestId.getSelectorColumns().add(new String[]{"requestQuantity", " Quantity", " align=\"center\" width=\"10%\" nowrap"});
        distributionRequestId.getSelectorColumns().add(new String[]{"requestDescription", " Description", "align=\"left\" width=\"60%\""});
        distributionRequestId.setSelectorOrder("t.requestNumber");
        getFields().add(distributionRequestId);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(distributionNumber);
        getFieldsAdd().add(distributionDate);
        getFieldsAdd().add(distributionRequestId);
//        getFieldsAdd().add(distributionRegionalId);
//        getFieldsAdd().add(distributionMainKitchenId);
        getFieldsAdd().add(distributionDistributorBy);
        getFieldsAdd().add(distributionDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(distributionNumber);
        getFieldsEdit().add(distributionDate);
//        getFieldsEdit().add(distributionMainKitchenId);
//        getFieldsEdit().add(distributionRegionalId);
//        getFieldsEdit().add(distributionPosUnitId);
        getFieldsEdit().add(distributionDistributorBy);
        getFieldsEdit().add(distributionDescription);

        getFieldsList().clear();
        getFieldsList().add(distributionNumber);
        getFieldsList().add(distributionDate);
        getFieldsList().add(distributionUnitId);
//        getFieldsList().add(distributionRegionalId);
        getFieldsList().add(distributionRequestId);
        getFieldsList().add(distributionTotal);
        getFieldsList().add(distributionSent);
        getFieldsList().add(distributionUnsent);
//        getFieldsList().add(distributionPosUnitId);
        getFieldsList().add(distributionDescription);
//        getFieldsList().add(distributionProgress);

        getFieldsView().clear();
        getFieldsView().add(distributionDate);
        getFieldsView().add(distributionNumber);
        getFieldsView().add(distributionUserId);
        getFieldsView().add(distributionUnitId);
//        getFieldsView().add(distributionRegionalId);
        getFieldsView().add(distributionTotal);
        getFieldsView().add(distributionPaid);
        getFieldsView().add(distributionUnpaid);
        getFieldsView().add(distributionKeel);
        getFieldsView().add(distributionDescription);
//        getFieldsView().add(distributionPosUnitId);
        getFieldsView().add(distributionTimestamp);

        setExportList(getClass().getResourceAsStream("DistributionList.jasper"));
        setExport(getClass().getResourceAsStream("Distribution.jasper"));
        
        
//        getActions().add(actionRevision);
//        getActions().add(actionAgree);
//        getActions().add(actionReject);

        setController(new Controller(this) {
            @Override
            public void beforeInsert(Object data, List list) {
                PosTransactionWhDistributionToOutlet receipt = (PosTransactionWhDistributionToOutlet) data;
                EntityManager em = getEntityManager();
                receipt.setDistributionNumber(generate());
                receipt.setDistributionUnitId(getCurrentUnit());
                receipt.setDistributionUserId(getCurrentUser());
                receipt.setDistributionTimestamp(Utility.getTimestamp());
//                receipt.setPurchaseOrderStatus("1");
//                receipt.setPurchaseOrderProgress("1");
//                receipt.setPurchaseOrderReceived(BigDecimal.ZERO);

                System.out.println("--> delete duplicate");
                for (int i = list.size() - 1; i > 0; i--) {
                    PosTransactionWhDistributionToOutletDetail d1 = (PosTransactionWhDistributionToOutletDetail) list.get(i);
                    System.out.println("-- " + d1.getDistributionDetailItemId());
                    for (int j = 0; j < i; j++) {
                        PosTransactionWhDistributionToOutletDetail d2 = (PosTransactionWhDistributionToOutletDetail) list.get(j);
                        System.out.println(d2.getDistributionDetailItemId() + " == " + d1.getDistributionDetailItemId());
                        if (d2.getDistributionDetailItemId().equals(d1.getDistributionDetailItemId())) {
                            d2.setDistributionDetailQuantity(d2.getDistributionDetailQuantity().add(d1.getDistributionDetailQuantity()));
                            System.out.println("Cekk Quantity ---1 :" + d2.getDistributionDetailQuantity());
                            list.remove(i);
                            break;
                        }
                        System.out.println("Cekk Quantity :" + d2.getDistributionDetailQuantity());
                    }
                }
            }

            @Override
            public void afterInsert(Object data, List list) {
                EntityManager em = getEntityManager();
                try {
                    em.getTransaction().begin();
                    PosTransactionWhDistributionToOutlet distribution = (PosTransactionWhDistributionToOutlet) data;
                    PosTransactionOutRequestMaterialToWarehouse request = distribution.getDistributionRequestId();
                    distribution.setDistributionRegionalId(request.getRequestRegionalId());
//                    distribution.setDistributionPosUnitId(distribution.getDistributionPosUnitId());
                    BigDecimal total = BigDecimal.ZERO;
                    BigDecimal totalQuantity = BigDecimal.ZERO;
                    PosMasterStatus statusGood = Status.getStatusGood(em);

//                    PosMasterRegional regional = (PosMasterRegional) em.createQuery("SELECT t FROM PosMasterRegional t"
//                        + " WHERE t.regionalId=1 ")
//                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                    PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
//                            + " WHERE t.unitUnitTypeId.unitTypeId=2 "
//                            + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId() //                        + " AND t.unitRegionalId.regionalId=1"
//                            )
//                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                    distribution.setDistributionRegionalId(posunit.getUnitRegionalId());
//                    distribution.setDistributionPosUnitId(posunit);
//                    System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName() + " regional :" + posunit.getUnitRegionalId());

                    for (Object detail : list) {
                        PosTransactionWhDistributionToOutletDetail distributionDetail = (PosTransactionWhDistributionToOutletDetail) detail;

                        PosMasterItemStock stock = Item.getStockItem(em, distributionDetail.getDistributionDetailItemId(),getCurrentUnit());
                        PosTransactionItemStock item = new PosTransactionItemStock();
                        item.setItemStockId(Sequence.next(item));
                        item.setItemStockItemId(distributionDetail.getDistributionDetailItemId());
//                        item.setItemStockRegionalId(posunit.getUnitRegionalId());
//                        item.setItemStockPosUnitId(posunit);
                        item.setItemStockStatusId(statusGood);
                        item.setItemStockType("3");
                        item.setItemStockLast(stock.getItemStockValue());
                        item.setItemStockValue(distributionDetail.getDistributionDetailQuantity());
                        item.setItemStockCurrent(stock.getItemStockValue().subtract(item.getItemStockValue()));
                        item.setItemStockUnitId(getCurrentUnit());
                        item.setItemStockUserId(getCurrentUser());
                        item.setItemStockTimestamp(Utility.getTimestamp());
                        em.persist(item);
                        stock.setItemStockValue(item.getItemStockCurrent());
                        stock.setItemStockTimestamp(distribution.getDistributionTimestamp());

                        total = total.add(distributionDetail.getDistributionDetailPrice().multiply(distributionDetail.getDistributionDetailQuantity()));
                        totalQuantity = totalQuantity.add(distributionDetail.getDistributionDetailQuantity());
                        distributionDetail.setDistributionDetailSent(BigDecimal.ZERO);
                        distributionDetail.setDistributionDetailUnsent(distributionDetail.getDistributionDetailQuantity());
                    }
                    distribution.setDistributionTotal(total);
                    distribution.setDistributionSent(BigDecimal.ZERO);
                    distribution.setDistributionUnsent(totalQuantity);
                    em.getTransaction().commit();
                } catch (Exception e) {
                    System.out.println("Errrr :"+e);
                }
            }
        });
    }

    @Override
    public void beforeAdd() {
        distributionNumber.setDefaultValue(generate());
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionWhDistributionToOutlet rec = (PosTransactionWhDistributionToOutlet) getEntityManager().createQuery("SELECT t FROM PosTransactionWhDistributionToOutlet t "
                    + "WHERE t.distributionNumber LIKE '%/" + unitCode + "/Rons/DIST-WH/%/" + year + "' "
                    + "ORDER BY t.distributionTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(rec.getDistributionNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/Rons/DIST-WH/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/Rons/DIST-WH/" + month + "/" + year;
    }
}
